package com.kifas.controller;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.kifas.entity.SatuanEntity;
import com.kifas.model.xml.PersistStatus;
import com.kifas.model.xml.SatuanModel;
import com.kifas.service.EntityServiceManager;

@Component
@Scope("prototype")
@Path("/Satuans")
public class SatuanController {

	private static Logger log = Logger.getLogger(SatuanController.class);

	@Context
	UriInfo uriInfo;

	@Autowired
	private EntityServiceManager entityManager;

	@GET
	@Produces(MediaType.TEXT_XML)
	public List<SatuanModel> getSatuans() {
		List<SatuanEntity> satuans = entityManager.getSatuans();
		return transformList(satuans);
	}

	@POST
	@Produces(MediaType.APPLICATION_XML)
	@Consumes(MediaType.APPLICATION_XML)
	public PersistStatus insert(JAXBElement<SatuanModel> xml) {
		SatuanModel model = xml.getValue();
		SatuanEntity satuan = new SatuanEntity(null, model.getSatuan(), model.getCreatedBy());
		try {
			entityManager.persist(satuan);
		} catch (Exception e) {
			log.error("can not persist satuan entity", e);
			return new PersistStatus("SatuanEntity", "failed", "can not persist satuan barang entity");
		}
		return new PersistStatus("SatuanEntity", "success");
	}

	@PUT
	@Consumes(MediaType.APPLICATION_XML)
	@Produces(MediaType.APPLICATION_XML)
	public PersistStatus update(JAXBElement<SatuanModel> xml) {
		SatuanModel model = xml.getValue();
		SatuanEntity satuan = new SatuanEntity(null, model.getSatuan(), model.getCreatedBy());
		try {
			entityManager.update(satuan);
		} catch (Exception e) {
			log.error("can not update satuan entity", e);
			return new PersistStatus("SatuanEntity", "failed", "can not update satuan barang entity");
		}
		return new PersistStatus("SatuanEntity", "success");
	}

	private SatuanModel transform(SatuanEntity satuan) {
		return new SatuanModel(satuan.getIdSatuan(), satuan.getSatuan(), satuan.getCreatedBy());
	}

	private List<SatuanModel> transformList(List<SatuanEntity> satuans) {
		List<SatuanModel> satuanEntities = new ArrayList<SatuanModel>();
		for (SatuanEntity satuan : satuans) {
			satuanEntities.add(transform(satuan));
		}
		return satuanEntities;

	}
}
